package com.yoosora.plugins;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.common.utils.RegexUtils;
import com.mikuac.shiro.common.utils.ShiroUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotPlugin;
import com.mikuac.shiro.dto.event.message.GroupMessageEvent;
import com.mikuac.shiro.dto.event.message.PrivateMessageEvent;
import com.yoosora.utils.FileUtils;
import com.yoosora.utils.RegexConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.util.List;

/**
 * @author yoosora
 */
@Slf4j
@Component
public class AnimeThesaurus extends BotPlugin {
	private final static String IMAGE_CQ_CODE = "[CQ:image";
	private final static String DEFAULT_MSG = "咱不明白你在说什么呢。";
	private static JSONObject jsonObject;
	private final static String filename = System.getProperty("user.dir") + File.separator + "anime_thesaurus.json";

	/**
	 * 加载方法
	 */
	@PostConstruct
	private void init() {
		if (FileUtils.isExists(filename)) {
			log.info("开始加载语言模块!");
			jsonObject = new JSONObject(FileUtils.readJsonString(filename));
			log.info("语言模块加载完成,模块大小[{}]", jsonObject.size());
		} else {
			log.info("语言模块不存在");
		}
	}

	private String getRespList(String msg) {
		for (String key : jsonObject.keySet()) {
			if (msg.contains(key)) {
				List<String> respWorldList = JSONArray.parseArray(jsonObject.get(key).toString(), String.class);
				return RandomUtil.randomEle(respWorldList);
			}
		}
		return null;
	}

	@Override
	public int onGroupMessage(@NotNull Bot bot, @NotNull GroupMessageEvent event) {
		String msg = event.getMessage();
		long groupId = event.getGroupId();
		int msgId = event.getMessageId();
		if (ShiroUtils.isAtAll(msg) || msg.contains(IMAGE_CQ_CODE)) {
			return MESSAGE_IGNORE;
		}
		// 判断被at的是否为机器人
		String atId = RegexUtils.regexGroup(RegexConst.GROUP_AT, msg, 1);
		if (atId != null && !atId.isEmpty()) {
//			if (Config.BOT_SELF_ID == botId) {
			if (atId.equals("2315160273")) {
				msg = msg.replace(String.format("[CQ:at,qq=%s] ", "2315160273"), "");
				String sendMsg = getRespList(msg);
				if (sendMsg == null) {
//					return MESSAGE_IGNORE;
					sendMsg = DEFAULT_MSG;
				}
				bot.sendGroupMsg(groupId, MsgUtils.builder().reply(msgId).text(sendMsg).build(), false);
			}
		}
		return MESSAGE_IGNORE;
	}

	@Override
	public int onPrivateMessage(@NotNull Bot bot, @NotNull PrivateMessageEvent event) {
		String msg = event.getMessage();
		long userId = event.getUserId();
		String sendMsg = getRespList(msg);
		if (msg.contains(IMAGE_CQ_CODE) || sendMsg == null) {
			return MESSAGE_IGNORE;
		}
		bot.sendPrivateMsg(userId, sendMsg, false);
		return MESSAGE_IGNORE;
	}

}
